<template>
  <div class="member-detail-page">
                <!-- 页面头部 -->
            <div class="page-header">
              <el-button @click="goBack" icon="ArrowLeft" type="primary" plain>
                返回会员列表
              </el-button>
              <h2 class="page-title">会员详情</h2>
              <div class="header-actions">
                <el-button 
                  :type="member.isBlacklisted ? 'success' : 'danger'"
                  @click="toggleBlacklist"
                  :disabled="member.status === '已注销'"
                >
                  {{ member.isBlacklisted ? '移出黑名单' : '拉黑' }}
                </el-button>
              </div>
            </div>

    <!-- 会员基本信息 -->
    <div class="member-info-card">
      <el-card>
        <div class="member-detail-header">
          <el-avatar :size="80" :src="member.avatar" />
          <div class="member-info">
            <div class="nickname">{{ member.nickname }}</div>
            <div class="id">{{ member.id }}</div>
            <div class="member-details">
              <span class="detail-item">等级：{{ member.level }}</span>
              <span class="detail-item">积分：{{ member.points }}</span>
              <span class="detail-item">当前余额：{{ member.balance || '¥0' }}</span>
              <span class="detail-item">会员类型：{{ member.memberType || 'B' }}</span>
            </div>
          </div>
        </div>
        
        <!-- 会员权限设置 -->
        <div class="member-permissions">
          <el-divider content-position="left">
            <el-icon><Setting /></el-icon>
            权限设置
          </el-divider>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="permission-item">
                <div class="permission-label">
                  <el-icon><Service /></el-icon>
                  <span>超级客服</span>
                </div>
                <div class="permission-control">
                  <el-switch 
                    v-model="member.superService" 
                    @change="handleSuperServiceChange"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <div class="permission-desc">
                    开启后该用户享受超级客服服务，优先处理问题
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="permission-item">
                <div class="permission-label">
                  <el-icon><View /></el-icon>
                  <span>数据全见</span>
                </div>
                <div class="permission-control">
                  <el-switch 
                    v-model="member.fullDataAccess" 
                    @change="handleFullDataAccessChange"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <div class="permission-desc">
                    开启后客户端可查看90天以上的历史数据
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>



    <!-- Tab内容 -->
    <div class="tab-content">
      <el-tabs v-model="activeTab" class="member-detail-tabs">
        <el-tab-pane label="用户信息" name="info">
          <UserInfoTab :member="member" />
        </el-tab-pane>
        <el-tab-pane label="支付明细" name="payment" v-if="member.memberType === 'B'">
          <PaymentDetailTab :member="member" />
        </el-tab-pane>
        <el-tab-pane label="费率设置" name="rates" v-if="member.memberType === 'B' || member.memberType === 'C'">
          <RateSettingsTab :member="member" @openRateDialog="openRateDialog" />
        </el-tab-pane>
        <el-tab-pane label="消费记录" name="orders">
          <OrderTab :orders="orders" />
        </el-tab-pane>
        <el-tab-pane label="收藏商品" name="favorite-goods">
          <FavoriteGoodsTab :favoriteGoods="favoriteGoods" />
        </el-tab-pane>
        <el-tab-pane label="收藏卖家" name="favorite-sellers">
          <FavoriteSellersTab :favoriteSellers="favoriteSellers" />
        </el-tab-pane>
        <el-tab-pane label="浏览足迹" name="footprints">
          <FootprintTab :footprints="footprints" />
        </el-tab-pane>
        <el-tab-pane label="搜索记录" name="search">
          <SearchTab :historySearch="historySearch" :recentSearch="recentSearch" />
        </el-tab-pane>
        <el-tab-pane label="邀请记录" name="referrals">
          <ReferralTab :referrals="referrals" />
        </el-tab-pane>
        <el-tab-pane label="福利中心" name="points">
          <el-tabs v-model="pointsActiveTab" class="points-sub-tabs">
            <el-tab-pane label="积分明细" name="points-detail">
              <PointsTab :pointsList="pointsList" />
            </el-tab-pane>
            <el-tab-pane label="成长记录" name="growth">
              <GrowthRecordTab />
            </el-tab-pane>
            <el-tab-pane label="签到记录" name="signins">
              <SigninTab :signinList="signinList" />
            </el-tab-pane>
            <el-tab-pane label="优惠券" name="coupons">
              <CouponTab :couponList="couponList" />
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 费率设置对话框 -->
    <el-dialog v-model="showRateDialog" title="费率设置" width="900px">
      <div class="rate-settings-container">
        <!-- 会员信息 -->
        <div class="member-info-section">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <label>会员ID：</label>
                <span>{{ rateForm.memberId }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>会员姓名：</label>
                <span>{{ rateForm.memberName }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>会员类型：</label>
                <span>{{ rateForm.memberType }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 设置项目选择 -->
        <div class="settings-selection">
          <h4>选择需要设置的项目</h4>
          <el-checkbox-group v-model="rateForm.selectedItems">
            <el-checkbox value="exchangeRate">汇率设置</el-checkbox>
            <el-checkbox value="serviceFee">手续费设置</el-checkbox>
            <el-checkbox v-if="rateForm.memberType === 'B'" value="serviceRate">服务费率设置</el-checkbox>
            <el-checkbox v-if="rateForm.memberType === 'B'" value="depositRatio">保证金比例设置</el-checkbox>
          </el-checkbox-group>
        </div>

        <!-- 汇率设置 -->
        <div v-if="rateForm.selectedItems.includes('exchangeRate')" class="rate-section">
          <h4>汇率设置</h4>
          <div class="rate-content">
            <!-- 汇率设置 -->
            <div class="exchange-rate-settings">
              <div class="rate-row">
                <label>实时汇率：</label>
                <div class="rate-input-group">
                  <el-input 
                    :value="(rateForm.realTimeRate || parseFloat(getDefaultExchangeRate())).toFixed(5)" 
                    readonly
                    style="width: 200px;"
                    placeholder="实时汇率"
                  />
                  <el-button 
                    type="info" 
                    size="small" 
                    @click="refreshExchangeRate"
                    style="margin-left: 8px;"
                  >
                    <el-icon><Refresh /></el-icon>
                    刷新汇率
                  </el-button>
                </div>
              </div>
              
              <div class="rate-row">
                <label>汇率差：</label>
                <div class="rate-difference-group">
                  <el-input-number 
                    v-model="rateForm.rateDifference" 
                    :precision="5" 
                    :step="0.00001" 
                    :min="-0.1" 
                    :max="0.1"
                    style="width: 200px;"
                    placeholder="汇率差"
                    @change="calculateActualRate"
                  />
                </div>
              </div>
              
              <div class="rate-row">
                <label>自定义汇率：</label>
                <div class="actual-rate-display">
                  <el-input 
                    :value="rateForm.actualExchangeRate ? rateForm.actualExchangeRate.toFixed(4) : ''" 
                    readonly
                    style="width: 200px;"
                    placeholder="自动计算"
                  />
                  <span class="rate-note">（实时汇率 + 汇率差）</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 手续费设置 -->
        <div v-if="rateForm.selectedItems.includes('serviceFee')" class="rate-section">
          <h4>手续费设置</h4>
          <div class="rate-content">

            
            <!-- 自定义手续费设置 -->
            <div class="custom-fee-settings">
              <div class="section-header">
                <span>自定义分站点分阶段手续费设置:</span>
                <el-button size="small" type="primary" @click="openServiceFeeDialog('add')">添加手续费</el-button>
              </div>
              
              <!-- 按站点分块显示 -->
              <div v-if="rateForm.serviceFeeRanges.length > 0" class="site-fee-blocks">
                <div v-for="site in getUniqueSites()" :key="site" class="site-fee-block">
                  <div class="block-header">
                    <el-icon class="site-icon"><Service /></el-icon>
                    <span class="site-name">{{ site }}</span>
                    <el-button size="small" type="primary" @click="openServiceFeeDialog('add', undefined, undefined, site)" class="add-btn">+新增</el-button>
                  </div>
                  
                  <div class="fee-table">
                    <div class="table-header">
                      <span class="header-cell">区间下限 (日元)</span>
                      <span class="header-cell">区间上限 (日元)</span>
                      <span class="header-cell">手续费 (日元)</span>
                      <span class="header-cell">操作</span>
                    </div>
                    
                    <div v-for="(feeItem, index) in getFeesBySite(site)" :key="`${site}-${index}`" class="table-row">
                      <span class="table-cell">{{ feeItem.minAmount || 0 }}</span>
                      <span class="table-cell">
                        <span v-if="feeItem.maxAmount && feeItem.maxAmount > 0">{{ feeItem.maxAmount }}</span>
                        <span v-else style="color: #909399;">无上限</span>
                      </span>
                      <span class="table-cell fee-amount">{{ feeItem.fee }}</span>
                      <div class="table-cell actions">
                        <el-button size="small" @click="openServiceFeeDialog('edit', feeItem, getGlobalIndex(feeItem))">编辑</el-button>
                        <el-button size="small" type="danger" @click="removeServiceFeeRange(getGlobalIndex(feeItem))">删除</el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 空状态 -->
              <div v-else class="empty-state">
                <el-empty description="暂无自定义手续费设置" :image-size="80">
                  <el-button type="primary" @click="openServiceFeeDialog('add')">添加第一个手续费设置</el-button>
                </el-empty>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 服务费率设置（仅B类客户） -->
        <div v-if="rateForm.selectedItems.includes('serviceRate') && rateForm.memberType === 'B'" class="rate-section">
          <h4>服务费率设置</h4>
          <div class="rate-content">
            <div class="base-info">
              <span>基础设置服务费率：{{ getDefaultServiceRate() }}%</span>
              <div v-if="getDefaultServiceRateSites().length > 0" style="margin-top: 8px;">
                <span style="font-size: 12px; color: #909399;">基础设置站点费率：</span>
                <el-tag v-for="site in getDefaultServiceRateSites()" :key="site.site" size="small" style="margin-right: 4px;">
                  {{ site.site }}: {{ site.rate }}%
                </el-tag>
              </div>
            </div>
            
            <!-- 服务费率表格 -->
            <div class="table-container">
              <div class="table-header">
                <span>站点费率设置</span>
                <el-button size="small" type="primary" @click="addServiceRateSite">添加站点</el-button>
              </div>
                             <el-table :data="rateForm.serviceRateSites" border style="width: 100%;">
                 <el-table-column prop="index" label="序号" width="60">
                   <template #default="{ $index }">
                     {{ $index + 1 }}
                   </template>
                 </el-table-column>
                 <el-table-column label="站点" width="180">
                   <template #default="{ row }">
                     <el-select v-model="row.site" placeholder="选择站点" style="width: 100%;">
                       <el-option label="煤炉" value="煤炉" />
                       <el-option label="雅虎日拍" value="雅虎日拍" />
                       <el-option label="乐天" value="乐天" />
                       <el-option label="亚马逊" value="亚马逊" />
                     </el-select>
                   </template>
                 </el-table-column>
                 <el-table-column label="费率" width="180">
                   <template #default="{ row }">
                     <el-input-number 
                       v-model="row.rate" 
                       :precision="1" 
                       :step="0.1" 
                       :min="0" 
                       :max="100"
                       style="width: 120px;"
                       placeholder="费率"
                     />
                     <span style="margin-left: 8px; font-size: 12px; color: #909399;">%</span>
                   </template>
                 </el-table-column>
                 <el-table-column label="操作" width="80">
                   <template #default="{ $index }">
                     <el-button size="small" type="danger" @click="removeServiceRateSite($index)">删除</el-button>
                   </template>
                 </el-table-column>
               </el-table>
            </div>
          </div>
        </div>
        
        <!-- 保证金比例设置（仅B类客户） -->
        <div v-if="rateForm.selectedItems.includes('depositRatio') && rateForm.memberType === 'B'" class="rate-section">
          <h4>保证金比例设置</h4>
          <div class="rate-content">
            <div class="base-info">
              <span>基础设置保证金比例：{{ getDefaultDepositRatio() }}%</span>
              <div v-if="getDefaultDepositRatioSites().length > 0" style="margin-top: 8px;">
                <span style="font-size: 12px; color: #909399;">基础设置站点比例：</span>
                <el-tag v-for="site in getDefaultDepositRatioSites()" :key="site.site" size="small" style="margin-right: 4px;">
                  {{ site.site }}: {{ site.ratio }}%
                </el-tag>
              </div>
            </div>
            
            <!-- 保证金比例表格 -->
            <div class="table-container">
              <div class="table-header">
                <span>站点比例设置</span>
                <el-button size="small" type="primary" @click="addDepositRatioSite">添加站点</el-button>
              </div>
                             <el-table :data="rateForm.depositRatioSites" border style="width: 100%;">
                 <el-table-column prop="index" label="序号" width="60">
                   <template #default="{ $index }">
                     {{ $index + 1 }}
                   </template>
                 </el-table-column>
                 <el-table-column label="站点" width="180">
                   <template #default="{ row }">
                     <el-select v-model="row.site" placeholder="选择站点" style="width: 100%;">
                       <el-option label="煤炉" value="煤炉" />
                       <el-option label="雅虎日拍" value="雅虎日拍" />
                       <el-option label="乐天" value="乐天" />
                       <el-option label="亚马逊" value="亚马逊" />
                     </el-select>
                   </template>
                 </el-table-column>
                 <el-table-column label="比例" width="180">
                   <template #default="{ row }">
                     <el-input-number 
                       v-model="row.ratio" 
                       :precision="1" 
                       :step="0.1" 
                       :min="0" 
                       :max="100"
                       style="width: 120px;"
                       placeholder="比例"
                     />
                     <span style="margin-left: 8px; font-size: 12px; color: #909399;">%</span>
                   </template>
                 </el-table-column>
                 <el-table-column label="操作" width="80">
                   <template #default="{ $index }">
                     <el-button size="small" type="danger" @click="removeDepositRatioSite($index)">删除</el-button>
                   </template>
                 </el-table-column>
               </el-table>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showRateDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmRateSettings">确认</el-button>
      </template>
    </el-dialog>

    <!-- 手续费设置弹窗 -->
    <el-dialog v-model="serviceFeeDialog.visible" :title="serviceFeeDialog.mode === 'add' ? '新增手续费' : '编辑手续费'" width="600px" :close-on-click-modal="false">
      <el-form :model="serviceFeeDialog.form" :rules="serviceFeeRules" ref="serviceFeeFormRef" label-width="120px">
        <el-form-item label="客户类型">
          <el-select v-model="serviceFeeDialog.form.type" style="width: 100%">
            <el-option label="B端客户" value="B" />
            <el-option label="C端客户" value="C" />
          </el-select>
        </el-form-item>
        <el-form-item label="站点">
          <el-select v-model="serviceFeeDialog.form.site" style="width: 100%">
            <el-option label="煤炉" value="煤炉" />
            <el-option label="亚马逊日本" value="亚马逊日本" />
            <el-option label="雅虎日拍" value="雅虎日拍" />
            <el-option label="乐天闲置" value="乐天闲置" />
          </el-select>
        </el-form-item>
        <el-form-item label="区间下限" prop="minAmount">
          <el-input-number v-model="serviceFeeDialog.form.minAmount" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="区间上限" prop="maxAmount">
          <el-input-number v-model="serviceFeeDialog.form.maxAmount" :min="0" style="width: 100%" />
          <span style="color:#888;font-size:12px;">留空或0表示无上限</span>
        </el-form-item>
        <el-form-item label="手续费" prop="fee">
          <el-input-number v-model="serviceFeeDialog.form.fee" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="serviceFeeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveServiceFee">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Setting, Service, View } from '@element-plus/icons-vue';
import { saveRateSettings, getRateSettings, testDatabaseConnection } from '@/services/database';
import { exchangeRateService } from '@/services/exchangeRateService';
import { baseSettingsService } from '@/services/baseSettingsService';
import UserInfoTab from './MemberDetailTabs/UserInfoTab.vue';
import OrderTab from './MemberDetailTabs/OrderTab.vue';
import PointsTab from './MemberDetailTabs/PointsTab.vue';
import SigninTab from './MemberDetailTabs/SigninTab.vue';
import GrowthRecordTab from './MemberDetailTabs/GrowthRecordTab.vue';
import CouponTab from './MemberDetailTabs/CouponTab.vue';
import FootprintTab from './MemberDetailTabs/FootprintTab.vue';
import SearchTab from './MemberDetailTabs/SearchTab.vue';
import ReferralTab from './MemberDetailTabs/ReferralTab.vue';
import FavoriteGoodsTab from './MemberDetailTabs/FavoriteGoodsTab.vue';
import FavoriteSellersTab from './MemberDetailTabs/FavoriteSellersTab.vue';
import PaymentDetailTab from './MemberDetailTabs/PaymentDetailTab.vue';
import RateSettingsTab from './MemberDetailTabs/RateSettingsTab.vue';

const route = useRoute();
const router = useRouter();
const activeTab = ref('info');
const pointsActiveTab = ref('points-detail');

// 从路由参数获取会员信息
const member = ref({
  avatar: '',
  nickname: '',
  level: 'L2',
  points: 5734,
  id: '',
  balance: '¥0',
  memberType: 'B',
  status: '在用',
  isBlacklisted: false,
  gender: '女',
  birthday: '2003-03-05',
  realName: '张三',
  idCard: '1102**********1110',
  phone: '+3348991137',
  wangwang: 'wangwang123',
  addressA: '中国大陆河北省廊坊市广阳区ABCD小区单元1101室, 张三, +3348991137',
  receiverA: '张三',
  phoneA: '+3348991137',
  addressB: '中国大陆北京市朝阳区ABCD小区单元1101室, 张三, +3348991137',
  receiverB: '张三',
  phoneB: '+3348991137',
  addressC: '中国大陆北京市平谷区ABCD小区单元1101室, 张三, +3348991137',
  receiverC: '张三',
  phoneC: '+3348991137',
  tags: ['高消费', '高频用户', '中客单价', '高贡献客户', '重要发展客户'],
  registerTime: '2025-03-07 18:23:56',
  lastLogin: '2025-06-07 20:23:56',
  // 费率相关属性
  exchangeRate: null as string | null,
  serviceFee: null as string | null,
  serviceFeeRanges: [] as any[],
  serviceRate: null as string | null,
  serviceRateSites: [] as any[],
  depositRatio: null as string | null,
  depositRatioSites: [] as any[],
  // 权限设置
  superService: false,
  fullDataAccess: false,
});

// 初始化会员数据
onMounted(async () => {
  const memberId = route.params.id as string;
  const memberNickname = route.params.nickname as string;
  
  // 根据会员ID获取会员信息
  member.value.id = memberId;
  member.value.nickname = decodeURIComponent(memberNickname || '用户');
  
  // 这里可以根据memberId从API获取完整的会员信息
  // 暂时使用模拟数据
  await loadMemberData(memberId);
  
  // 设置默认的余额
  member.value.balance = '¥0'; // 默认余额
  
  // 确保汇率服务已启动
  if (exchangeRateService) {
    console.log('汇率服务已启动，当前汇率:', exchangeRateService.getCurrentRate())
  }
});

// 加载会员数据
async function loadMemberData(memberId: string) {
  // 这里应该调用API获取会员详细信息
  // 暂时使用模拟数据
  console.log('加载会员数据:', memberId);
  
  // 模拟会员数据，包含自动标签和手动标签
  const mockMemberData = {
    id: memberId,
    nickname: decodeURIComponent(route.params.nickname as string || '用户'),
    realName: `姓名${memberId.slice(-2)}`,
    phone: `+33${String(480000000 + parseInt(memberId.slice(-2))).slice(1)}`,
    wangwang: `wangwang${memberId.slice(-2)}`,
    gender: ['男', '女', '未知'][parseInt(memberId.slice(-2)) % 3],
    birthday: '1990-01-01',
    idCard: '110101199001011234',
    addressA: '北京市朝阳区某某街道123号',
    receiverA: `收件人${memberId.slice(-2)}`,
    phoneA: `+33${String(480000000 + parseInt(memberId.slice(-2))).slice(1)}`,
    addressB: '上海市浦东新区某某路456号',
    receiverB: `备用收件人${memberId.slice(-2)}`,
    phoneB: `+33${String(480000000 + parseInt(memberId.slice(-2)) + 1).slice(1)}`,
    addressC: '深圳市南山区某某大厦789号',
    receiverC: `工作收件人${memberId.slice(-2)}`,
    phoneC: `+33${String(480000000 + parseInt(memberId.slice(-2)) + 2).slice(1)}`,
    registerTime: '2024-06-04 12:02:00',
    lastLogin: '2024-12-07 20:23:56',
    tags: ['新用户', '活跃', 'VIP客户', '重要客户'], // 包含自动标签和手动标签
    memberType: (parseInt(memberId) - 10001) % 2 === 0 ? 'B' : 'C',
    balance: '¥0',
    level: 'L2',
    points: 1500,
    // 权限设置初始值
    superService: false,
    fullDataAccess: false
  };
  
  // 更新会员对象
  Object.assign(member.value, mockMemberData);
  
  // 从数据库加载费率设置
  try {
    const savedSettings = await getRateSettings(memberId)
    if (savedSettings) {
      console.log('从数据库加载会员费率设置:', savedSettings)
      
      // 更新会员对象的费率设置
      if (savedSettings.exchange_rate) {
        member.value.exchangeRate = savedSettings.exchange_rate
      }
      if (savedSettings.service_fee) {
        member.value.serviceFee = savedSettings.service_fee
      }
      if (savedSettings.service_fee_ranges) {
        try {
          member.value.serviceFeeRanges = JSON.parse(savedSettings.service_fee_ranges)
        } catch (error) {
          console.error('解析service_fee_ranges失败:', error)
        }
      }
      if (savedSettings.service_rate) {
        member.value.serviceRate = savedSettings.service_rate
      }
      if (savedSettings.service_rate_sites) {
        try {
          member.value.serviceRateSites = JSON.parse(savedSettings.service_rate_sites)
        } catch (error) {
          console.error('解析service_rate_sites失败:', error)
        }
      }
      if (savedSettings.deposit_ratio) {
        member.value.depositRatio = savedSettings.deposit_ratio
      }
      if (savedSettings.deposit_ratio_sites) {
        try {
          member.value.depositRatioSites = JSON.parse(savedSettings.deposit_ratio_sites)
        } catch (error) {
          console.error('解析deposit_ratio_sites失败:', error)
        }
      }
    } else {
      console.log('没有找到保存的费率设置')
    }
  } catch (error) {
    console.error('加载费率设置失败:', error)
  }
}

// 返回上一页
function goBack() {
  router.back();
}

// 处理超级客服开关变化
function handleSuperServiceChange(enabled: boolean) {
  const action = enabled ? '开启' : '关闭';
  ElMessage.success(`已${action}超级客服服务`);
  
  // 这里可以调用API保存设置
  console.log(`会员 ${member.value.id} 超级客服状态: ${enabled}`);
}

// 处理数据全见开关变化
function handleFullDataAccessChange(enabled: boolean) {
  const action = enabled ? '开启' : '关闭';
  ElMessage.success(`已${action}数据全见权限`);
  
  // 这里可以调用API保存设置
  console.log(`会员 ${member.value.id} 数据全见权限: ${enabled}`);
}



// 费率设置对话框
const showRateDialog = ref(false)
const rateForm = ref({
  memberId: '',
  memberName: '',
  memberType: '',
  selectedItems: [] as string[],
  exchangeRate: null as number | null,
  exchangeRateType: 'default' as 'default' | 'custom',
  realTimeRate: null as number | null,
  rateDifference: 0 as number,
  actualExchangeRate: null as number | null,
  serviceFee: null as number | null,
  serviceFeeType: 'default' as 'default' | 'custom',
  serviceFeeRanges: [] as Array<{type: string, site: string, minAmount: number | null, maxAmount: number | null, fee: number}>,
  serviceRate: null as number | null,
  serviceRateType: 'default' as 'default' | 'custom',
  serviceRateSites: [] as Array<{site: string, rate: number}>,
  depositRatio: null as number | null,
  depositRatioType: 'default' as 'default' | 'custom',
  depositRatioSites: [] as Array<{site: string, ratio: number}>
})

// 手续费设置弹窗
const serviceFeeDialog = ref({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  editIndex: -1,
  form: {
    type: 'B',
    site: '煤炉',
    minAmount: 0,
    maxAmount: 0,
    fee: 0
  }
})

// 手续费表单验证规则
const serviceFeeRules = {
  minAmount: [
    { required: true, message: '请输入区间下限', trigger: 'blur' }
  ],
  fee: [
    { required: true, message: '请输入手续费', trigger: 'blur' }
  ]
}

// 手续费表单引用
const serviceFeeFormRef = ref()

// 打开费率设置对话框
async function openRateDialog(memberData: any) {
  try {
    // 初始化费率表单
    rateForm.value.memberId = memberData.id
    rateForm.value.memberName = memberData.nickname
    rateForm.value.memberType = memberData.memberType
    
    // 从数据库加载费率设置
    const savedSettings = await getRateSettings(memberData.id)
    if (savedSettings) {
      console.log('从数据库加载费率设置:', savedSettings)
      
      // 设置汇率相关
      if (savedSettings.exchange_rate) {
        rateForm.value.exchangeRateType = 'custom'
        rateForm.value.exchangeRate = parseFloat(savedSettings.exchange_rate)
        rateForm.value.realTimeRate = parseFloat(getDefaultExchangeRate())
        rateForm.value.rateDifference = parseFloat(savedSettings.exchange_rate) - parseFloat(getDefaultExchangeRate())
        rateForm.value.actualExchangeRate = parseFloat(savedSettings.exchange_rate)
        rateForm.value.selectedItems.push('exchangeRate')
      } else {
        rateForm.value.exchangeRateType = 'default'
        rateForm.value.exchangeRate = parseFloat(getDefaultExchangeRate())
        rateForm.value.realTimeRate = parseFloat(getDefaultExchangeRate())
        rateForm.value.rateDifference = 0
        rateForm.value.actualExchangeRate = parseFloat(getDefaultExchangeRate())
      }
      
      // 设置手续费相关
      if (savedSettings.service_fee) {
        rateForm.value.serviceFeeType = 'custom'
        rateForm.value.serviceFee = parseFloat(savedSettings.service_fee)
        rateForm.value.selectedItems.push('serviceFee')
        // 初始化多价格区间信息
        if (savedSettings.service_fee_ranges) {
          try {
            rateForm.value.serviceFeeRanges = JSON.parse(savedSettings.service_fee_ranges)
          } catch (error) {
            console.error('解析service_fee_ranges失败:', error)
            rateForm.value.serviceFeeRanges = [{
              type: 'B',
              site: '煤炉',
              minAmount: 0,
              maxAmount: 10000,
              fee: parseFloat(savedSettings.service_fee)
            }]
          }
        } else {
          // 默认添加一个价格区间
          rateForm.value.serviceFeeRanges = [{
            type: 'B',
            site: '煤炉',
            minAmount: 0,
            maxAmount: 10000,
            fee: parseFloat(savedSettings.service_fee)
          }]
        }
      } else {
        rateForm.value.serviceFeeType = 'default'
        rateForm.value.serviceFee = null
        rateForm.value.serviceFeeRanges = []
      }
      
      // 设置服务费率相关（仅B类客户）
      if (savedSettings.service_rate) {
        rateForm.value.serviceRateType = 'custom'
        rateForm.value.serviceRate = parseFloat(savedSettings.service_rate.replace('%', ''))
        rateForm.value.selectedItems.push('serviceRate')
        // 初始化多站点费率设置
        if (savedSettings.service_rate_sites) {
          try {
            rateForm.value.serviceRateSites = JSON.parse(savedSettings.service_rate_sites)
          } catch (error) {
            console.error('解析service_rate_sites失败:', error)
            rateForm.value.serviceRateSites = [
              { site: '煤炉', rate: parseFloat(savedSettings.service_rate.replace('%', '')) }
            ]
          }
        } else {
          rateForm.value.serviceRateSites = [
            { site: '煤炉', rate: parseFloat(savedSettings.service_rate.replace('%', '')) }
          ]
        }
      } else {
        rateForm.value.serviceRateType = 'default'
        rateForm.value.serviceRate = null
        // 从基础设置获取默认的服务费率站点
        rateForm.value.serviceRateSites = getDefaultServiceRateSites()
      }
      
      // 设置保证金比例相关（仅B类客户）
      if (savedSettings.deposit_ratio) {
        rateForm.value.depositRatioType = 'custom'
        rateForm.value.depositRatio = parseFloat(savedSettings.deposit_ratio.replace('%', ''))
        rateForm.value.selectedItems.push('depositRatio')
        // 初始化多站点比例设置
        if (savedSettings.deposit_ratio_sites) {
          try {
            rateForm.value.depositRatioSites = JSON.parse(savedSettings.deposit_ratio_sites)
          } catch (error) {
            console.error('解析deposit_ratio_sites失败:', error)
            rateForm.value.depositRatioSites = [
              { site: '煤炉', ratio: parseFloat(savedSettings.deposit_ratio.replace('%', '')) }
            ]
          }
        } else {
          rateForm.value.depositRatioSites = [
            { site: '煤炉', ratio: parseFloat(savedSettings.deposit_ratio.replace('%', '')) }
          ]
        }
      } else {
        rateForm.value.depositRatioType = 'default'
        rateForm.value.depositRatio = null
        // 从基础设置获取默认的保证金比例站点
        rateForm.value.depositRatioSites = getDefaultDepositRatioSites()
      }
    } else {
      // 如果没有保存的设置，使用默认值
      console.log('没有找到保存的费率设置，使用默认值')
      
      // 设置汇率相关
      if (memberData.exchangeRate) {
        rateForm.value.exchangeRateType = 'custom'
        rateForm.value.exchangeRate = parseFloat(memberData.exchangeRate)
        rateForm.value.realTimeRate = parseFloat(getDefaultExchangeRate())
        rateForm.value.rateDifference = parseFloat(memberData.exchangeRate) - parseFloat(getDefaultExchangeRate())
        rateForm.value.actualExchangeRate = parseFloat(memberData.exchangeRate)
        rateForm.value.selectedItems.push('exchangeRate')
      } else {
        rateForm.value.exchangeRateType = 'default'
        rateForm.value.exchangeRate = parseFloat(getDefaultExchangeRate())
        rateForm.value.realTimeRate = parseFloat(getDefaultExchangeRate())
        rateForm.value.rateDifference = 0
        rateForm.value.actualExchangeRate = parseFloat(getDefaultExchangeRate())
      }
      
      // 设置手续费相关
      if (memberData.serviceFee) {
        rateForm.value.serviceFeeType = 'custom'
        rateForm.value.serviceFee = parseFloat(memberData.serviceFee)
        rateForm.value.selectedItems.push('serviceFee')
        // 初始化多价格区间信息
        if (memberData.serviceFeeRanges && memberData.serviceFeeRanges.length > 0) {
          rateForm.value.serviceFeeRanges = memberData.serviceFeeRanges
        } else {
          // 默认添加一个价格区间
          rateForm.value.serviceFeeRanges = [{
            type: 'B',
            site: '煤炉',
            minAmount: 0,
            maxAmount: 10000,
            fee: parseFloat(memberData.serviceFee)
          }]
        }
      } else {
        rateForm.value.serviceFeeType = 'default'
        rateForm.value.serviceFee = null
        rateForm.value.serviceFeeRanges = []
      }
      
      // 设置服务费率相关（仅B类客户）
      if (memberData.serviceRate) {
        rateForm.value.serviceRateType = 'custom'
        rateForm.value.serviceRate = parseFloat(memberData.serviceRate.replace('%', ''))
        rateForm.value.selectedItems.push('serviceRate')
        // 初始化多站点费率设置
        if (memberData.serviceRateSites && memberData.serviceRateSites.length > 0) {
          rateForm.value.serviceRateSites = memberData.serviceRateSites
        } else {
          rateForm.value.serviceRateSites = [
            { site: '煤炉', rate: parseFloat(memberData.serviceRate.replace('%', '')) }
          ]
        }
      } else {
        rateForm.value.serviceRateType = 'default'
        rateForm.value.serviceRate = null
        // 从基础设置获取默认的服务费率站点
        rateForm.value.serviceRateSites = getDefaultServiceRateSites()
      }
      
      // 设置保证金比例相关（仅B类客户）
      if (memberData.depositRatio) {
        rateForm.value.depositRatioType = 'custom'
        rateForm.value.depositRatio = parseFloat(memberData.depositRatio.replace('%', ''))
        rateForm.value.selectedItems.push('depositRatio')
        // 初始化多站点比例设置
        if (memberData.depositRatioSites && memberData.depositRatioSites.length > 0) {
          rateForm.value.depositRatioSites = memberData.depositRatioSites
        } else {
          rateForm.value.depositRatioSites = [
            { site: '煤炉', ratio: parseFloat(memberData.depositRatio.replace('%', '')) }
          ]
        }
      } else {
        rateForm.value.depositRatioType = 'default'
        rateForm.value.depositRatio = null
        // 从基础设置获取默认的保证金比例站点
        rateForm.value.depositRatioSites = getDefaultDepositRatioSites()
      }
    }
    
    // 确保实时汇率有值，优先使用汇率服务中的最新汇率
    if (rateForm.value.realTimeRate === null) {
      const currentRate = exchangeRateService.getCurrentRate()
      rateForm.value.realTimeRate = parseFloat(currentRate)
    }
    
    // 初始化汇率计算
    calculateActualRate()
    
    showRateDialog.value = true
  } catch (error) {
    console.error('加载费率设置失败:', error)
    ElMessage.error('加载费率设置失败，请重试')
  }
}

// 汇率设置相关函数
function getDefaultExchangeRate() {
  // 获取基础设置中保存的实际汇率
  const savedActualRate = localStorage.getItem('exchangeRate')
  if (savedActualRate) {
    return parseFloat(savedActualRate).toFixed(4)
  }
  
  // 如果没有保存的实际汇率，则使用汇率服务中的当前汇率
  return exchangeRateService.getCurrentRate()
}

// 计算实际汇率
function calculateActualRate() {
  if (rateForm.value.realTimeRate !== null && rateForm.value.rateDifference !== null) {
    // 向上取整到小数点后4位
    const result = rateForm.value.realTimeRate + rateForm.value.rateDifference
    rateForm.value.actualExchangeRate = Math.ceil(result * 10000) / 10000
  }
}

// 刷新汇率（从服务获取最新汇率）
async function refreshExchangeRate() {
  try {
    // 调用真实汇率API获取最新汇率，与基础设置页面保持一致
    const res = await fetch('https://api.exchangerate-api.com/v4/latest/USD')
    const data = await res.json()
    if (data && data.rates && data.rates.CNY && data.rates.JPY) {
      // 1 JPY = (CNY/USD) / (JPY/USD) = CNY/JPY
      const cnyPerUsd = data.rates.CNY
      const jpyPerUsd = data.rates.JPY
      const jpyToCny = cnyPerUsd / jpyPerUsd
      const newRate = jpyToCny.toFixed(5)
      
      // 更新汇率服务
      exchangeRateService.setRate(newRate, '会员详情页刷新')
      
      // 更新表单中的实时汇率
      rateForm.value.realTimeRate = parseFloat(newRate)
      calculateActualRate()
      
      ElMessage.success('汇率已刷新')
    } else {
      ElMessage.error('获取汇率失败')
    }
  } catch (error) {
    console.error('刷新汇率失败:', error)
    ElMessage.error('汇率刷新失败，请重试')
  }
}



function getDefaultServiceFee(exchangeRate: string, site?: string) {
  // 根据会员类型和站点获取手续费
  // 这里使用一个示例金额来计算手续费，实际应该根据订单金额计算
  const exampleAmount = 10000 // 示例金额10000円
  if (member.value.memberType === 'B') {
    return baseSettingsService.getServiceFeeForB(exampleAmount, site || '煤炉').toString()
  } else if (member.value.memberType === 'C') {
    return baseSettingsService.getServiceFeeForC(exampleAmount, site || '雅虎日拍').toString()
  }
  return '200' // 默认手续费
}

// 获取默认服务费率（按站点）
function getDefaultServiceRate(site?: string) {
  // 只有B类客户有服务费率
  if (member.value.memberType === 'B') {
    const settings = baseSettingsService.getServiceRateSettings()
    if (site) {
      // 如果指定了站点，查找该站点的费率
      const siteSetting = settings.find(s => s.site === site)
      if (siteSetting) {
        return siteSetting.rate.toString()
      }
    }
    // 如果没有指定站点或找不到该站点，返回第一个费率
    if (settings.length > 0) {
      return settings[0].rate.toString()
    }
    return '3.5' // 默认服务费率
  }
  return '0'
}

// 获取默认保证金比例（按站点）
function getDefaultDepositRatio(site?: string) {
  // 只有B类客户有保证金比例
  if (member.value.memberType === 'B') {
    const settings = baseSettingsService.getDepositRateSettings()
    if (site) {
      // 如果指定了站点，查找该站点的比例
      const siteSetting = settings.find(s => s.site === site)
      if (siteSetting) {
        return siteSetting.rate.toString()
      }
    }
    // 如果没有指定站点或找不到该站点，返回第一个比例
    if (settings.length > 0) {
      return settings[0].rate.toString()
    }
    return '10.0' // 默认保证金比例
  }
  return '0'
}

// 获取所有站点的默认服务费率
function getDefaultServiceRateSites() {
  if (member.value.memberType === 'B') {
    const settings = baseSettingsService.getServiceRateSettings()
    return settings.map(s => ({
      site: s.site,
      rate: s.rate
    }))
  }
  return []
}

// 获取所有站点的默认手续费
function getDefaultServiceFeeSites() {
  const exampleAmount = 10000 // 示例金额10000円
  if (member.value.memberType === 'B') {
    const settings = baseSettingsService.getServiceFeeSettings('B')
    return settings.map(s => ({
      site: s.site,
      fee: s.fee
    }))
  } else if (member.value.memberType === 'C') {
    const settings = baseSettingsService.getServiceFeeSettings('C')
    return settings.map(s => ({
      site: s.site,
      fee: s.fee
    }))
  }
  return []
}

// 获取所有站点的默认保证金比例
function getDefaultDepositRatioSites() {
  if (member.value.memberType === 'B') {
    const settings = baseSettingsService.getDepositRateSettings()
    return settings.map(s => ({
      site: s.site,
      ratio: s.rate
    }))
  }
  return []
}

// 删除手续费区间
function removeServiceFeeRange(index: number) {
  ElMessageBox.confirm('确定要删除这条手续费设置吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    rateForm.value.serviceFeeRanges.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

// 获取唯一站点列表
function getUniqueSites() {
  const sites = rateForm.value.serviceFeeRanges.map(item => item.site)
  return [...new Set(sites)]
}

// 根据站点获取手续费设置
function getFeesBySite(site: string) {
  return rateForm.value.serviceFeeRanges.filter(item => item.site === site)
}

// 获取全局索引
function getGlobalIndex(feeItem: any) {
  return rateForm.value.serviceFeeRanges.findIndex(item => 
    item.site === feeItem.site && 
    item.minAmount === feeItem.minAmount && 
    item.maxAmount === feeItem.maxAmount && 
    item.fee === feeItem.fee
  )
}

// 添加服务费率站点
function addServiceRateSite() {
  rateForm.value.serviceRateSites.push({
    site: '煤炉',
    rate: 3.5
  })
}

// 删除服务费率站点
function removeServiceRateSite(index: number) {
  rateForm.value.serviceRateSites.splice(index, 1)
}

// 添加保证金比例站点
function addDepositRatioSite() {
  rateForm.value.depositRatioSites.push({
    site: '煤炉',
    ratio: 10.0
  })
}

// 删除保证金比例站点
function removeDepositRatioSite(index: number) {
  rateForm.value.depositRatioSites.splice(index, 1)
}

// 确认费率设置
async function confirmRateSettings() {
  try {
    console.log('开始确认费率设置...')
    console.log('当前会员信息:', member.value)
    console.log('费率表单数据:', rateForm.value)

    // 更新会员数据
    if (rateForm.value.selectedItems.includes('exchangeRate') && rateForm.value.actualExchangeRate) {
      member.value.exchangeRate = rateForm.value.actualExchangeRate.toString()
    } else {
      member.value.exchangeRate = null
    }

    if (rateForm.value.selectedItems.includes('serviceFee') && rateForm.value.serviceFeeRanges.length > 0) {
      const firstRange = rateForm.value.serviceFeeRanges[0]
      member.value.serviceFee = firstRange.fee?.toString() || '0'
      member.value.serviceFeeRanges = rateForm.value.serviceFeeRanges
    } else {
      member.value.serviceFee = null
      member.value.serviceFeeRanges = []
    }

    if (member.value.memberType === 'B') {
      if (rateForm.value.selectedItems.includes('serviceRate') && rateForm.value.serviceRateSites.length > 0) {
        const firstSite = rateForm.value.serviceRateSites[0]
        member.value.serviceRate = `${firstSite.rate}%`
        member.value.serviceRateSites = rateForm.value.serviceRateSites
      } else {
        member.value.serviceRate = null
        member.value.serviceRateSites = []
      }

      if (rateForm.value.selectedItems.includes('depositRatio') && rateForm.value.depositRatioSites.length > 0) {
        const firstSite = rateForm.value.depositRatioSites[0]
        member.value.depositRatio = `${firstSite.ratio}%`
        member.value.depositRatioSites = rateForm.value.depositRatioSites
      } else {
        member.value.depositRatio = null
        member.value.depositRatioSites = []
      }
    }

    // 保存到数据库 - 将数组转换为JSON字符串以避免克隆问题
    const rateSettings = {
      id: `rate_${member.value.id}`, // 使用固定的ID，这样会更新现有记录而不是创建新记录
      member_id: member.value.id,
      exchange_rate: member.value.exchangeRate,
      service_fee: member.value.serviceFee,
      service_fee_ranges: member.value.serviceFeeRanges ? JSON.stringify(member.value.serviceFeeRanges) : null,
      service_rate: member.value.serviceRate,
      service_rate_sites: member.value.serviceRateSites ? JSON.stringify(member.value.serviceRateSites) : null,
      deposit_ratio: member.value.depositRatio,
      deposit_ratio_sites: member.value.depositRatioSites ? JSON.stringify(member.value.depositRatioSites) : null,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    }

    console.log('准备保存的费率设置数据:', rateSettings)

    // 先测试数据库连接
    const dbTestResult = await testDatabaseConnection()
    if (!dbTestResult) {
      throw new Error('数据库连接测试失败，请检查浏览器设置')
    }

    await saveRateSettings(rateSettings)
    ElMessage.success('费率设置已保存到数据库')
    showRateDialog.value = false
  } catch (error: any) {
    console.error('保存费率设置失败:', error)
    console.error('错误堆栈:', error.stack)
    ElMessage.error(`保存费率设置失败，请重试。错误信息: ${error.message || '未知错误'}`)
  }
}

// 拉黑/移出黑名单
function toggleBlacklist() {
  const action = member.value.isBlacklisted ? '移出黑名单' : '拉黑';
  ElMessageBox.confirm(`确定要将用户【${member.value.nickname}】${action}吗？`, `确认${action}`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    member.value.isBlacklisted = !member.value.isBlacklisted;
    ElMessage.success(`${action}成功`);
  }).catch(() => {
    ElMessage.info(`已取消${action}操作`);
  });
}

// mock数据
const orders = ref([
  { id: 'ORDER_0001', name: 'ノートパソコン', count: 1, price: 8562, fee: 200, extra: 294, freight: 198, coupon: 300, point: 100, rate: 0.052, pay: '8000/416', time: '2025-06-09 12:30:11' },
  { id: 'ORDER_0002', name: 'スマートフォン', count: 1, price: 1254, fee: 200, extra: 198, freight: 156, coupon: 90, point: 50, rate: 0.052, pay: '1200/62', time: '2025-06-09 13:10:22' },
]);
const pointsList = ref([
  { id: 'TX20250601830001', type: '增加', way: '签到积分', before: 100, change: 5, after: 105, time: '2025-06-01 08:30:15', effectiveTime: '2025-06-01 08:30:15', expire: '2025-12-31', biz: 'ORDER_0001', operator: '管理员A', channel: '后台', remark: '每日签到' },
  { id: 'TX20250602145002', type: '增加', way: '购物赠送', before: 105, change: 150, after: 255, time: '2025-06-02 11:45:22', effectiveTime: '2025-06-02 11:45:22', expire: '2025-12-31', biz: 'ORDER_0002', operator: '系统', channel: '自动', remark: '订单完成赠送' },
]);
const signinList = ref([
  { idx: 1, point: 10, time: '2025-06-07 15:30:59', remark: '' },
  { idx: 2, point: 10, time: '2025-06-06 15:30:59', remark: '' },
]);
const couponList = ref([
  { idx: 1, name: '全平台免手续费', value: '300日元', period: '2025-06-09~2025-06-31', receiveTime: '2025-06-05 14:30:25', status: '已使用' },
  { idx: 2, name: '全平台免手续费', value: '300日元', period: '2025-06-09~2025-06-31', receiveTime: '2025-06-08 09:15:42', status: '未使用' },
  { idx: 3, name: '新人专享券', value: '500日元', period: '2025-06-10~2025-06-30', receiveTime: '2025-06-10 16:45:18', status: '未使用' },
  { idx: 4, name: '满减优惠券', value: '200日元', period: '2025-06-01~2025-06-15', receiveTime: '2025-06-01 11:20:33', status: '已过期' },
  { idx: 5, name: '生日特惠券', value: '1000日元', period: '2025-06-15~2025-07-15', receiveTime: '2025-06-15 08:30:55', status: '未使用' },
]);
const footprints = ref([
  { idx: 1, product: '★ベンツ X290 GT43 GT53 GT50用GT63AMGタイプフロント、リアエアロセット/バンパー/ディフューザー/テールパイプ/C190/4ドアクーペ', price: 688000, time: '2025-06-09 12:30:11', category: '汽车配件/奔驰配件/外观套件', image: 'https://img.idora.jp/upload/2024/01/15/benz-gt63-688000.jpg', goodsId: 'q1176960854' },
  { idx: 2, product: 'Z7a②⑨7/4 サッカー ノート Japan コーリン 当時物 昭和レトロ デッドストック', price: 950, time: '2025-06-09 13:10:22', category: '收藏品/文具收藏/笔记本', image: 'https://img.idora.jp/upload/2024/01/15/soccer-notebook-950.jpg', goodsId: 'q1176960855' },
]);
const historySearch = ref([
  { idx: 1, site: '煤炉', name: '香奈儿-限额', condition: '站点-香奈儿-香水-价格区间:10000-20000元', subscribe: '是', time: '2025-05-05 19:20:30' },
  { idx: 2, site: '雅虎日拍', name: '苹果手机-新品', condition: '品牌-苹果-手机-新品上市', subscribe: '否', time: '2025-05-06 10:15:45' },
]);
const recentSearch = ref([
  { idx: 1, name: '香奈儿-限额', condition: '站点-香奈儿-香水-价格区间:10000-20000元', time: '2025-05-05 19:20:30' },
  { idx: 2, name: '苹果手机-新品', condition: '品牌-苹果-手机-新品上市', time: '2025-05-06 10:15:45' },
]);
const referrals = ref([
  { uid: 1, nickname: '用户_2', contact: '+8683984196628', inviteTime: '2025-06-09 18:20:39', downloaded: '是' },
  { uid: 2, nickname: '用户_3', contact: '+8683984196629', inviteTime: '2025-06-10 14:30:25', downloaded: '否' },
]);
const favoriteGoods = ref([
  { idx: 1, product: 'DYSON ダイソン 純正 伸縮式パイプ 延長パイプ 適合：DC36/DC48/DC46/DC63 タービンヘッド用', price: 1600, time: '2025-06-09 12:30:11', category: '家电用品/清洁用品/吸尘器配件', image: 'https://img.idora.jp/upload/2024/01/15/dyson-pipe-1600.jpg', goodsId: 'q1176960852' },
  { idx: 2, product: 'ステンレス マフラー 51mm 63mm 変換パイプ 溶接 差し込み 部材 変換 パイプ バイク レースカー', price: 1500, time: '2025-06-09 13:10:22', category: '汽车配件/摩托车配件/排气管', image: 'https://img.idora.jp/upload/2024/01/15/stainless-pipe-1500.jpg', goodsId: 'q1176960853' },
]);
const favoriteSellers = ref([
  { idx: 1, nickname: '卖家A', contact: '+8613800138000', time: '2025-06-09 12:30:11' },
  { idx: 2, nickname: '卖家B', contact: '+8613900139000', time: '2025-06-09 13:10:22' },
]);

// 手续费设置相关函数
function openServiceFeeDialog(mode: 'add' | 'edit', row?: any, index?: number, presetSite?: string) {
  serviceFeeDialog.value.mode = mode
  serviceFeeDialog.value.editIndex = index !== undefined ? index : -1
  
  if (mode === 'add') {
    // 新增模式
    serviceFeeDialog.value.form = {
      type: 'B',
      site: presetSite || '煤炉',
      minAmount: 0,
      maxAmount: 0,
      fee: 0
    }
  } else {
    // 编辑模式
    serviceFeeDialog.value.form = {
      type: row.type || 'B',
      site: row.site || '煤炉',
      minAmount: row.minAmount || 0,
      maxAmount: row.maxAmount || 0,
      fee: row.fee || 0
    }
  }
  
  serviceFeeDialog.value.visible = true
}

// 保存手续费设置
function saveServiceFee() {
  if (!serviceFeeFormRef.value) return
  
  serviceFeeFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const formData = { ...serviceFeeDialog.value.form }
      
      if (serviceFeeDialog.value.mode === 'add') {
        // 新增
        rateForm.value.serviceFeeRanges.push(formData)
      } else {
        // 编辑
        const index = serviceFeeDialog.value.editIndex
        if (index >= 0 && index < rateForm.value.serviceFeeRanges.length) {
          rateForm.value.serviceFeeRanges[index] = formData
        }
      }
      
      ElMessage.success('手续费设置已保存')
      serviceFeeDialog.value.visible = false
    }
  })
}
</script>

<style scoped>
.member-detail-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.member-info-card {
  margin-bottom: 24px;
}

.member-info-card :deep(.el-card) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
}

.member-detail-header {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  padding: 8px 0;
}

.member-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.nickname {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.level {
  font-size: 14px;
  color: #606266;
  margin: 0;
  font-weight: 500;
}

.member-details {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 4px;
}

.detail-item {
  font-size: 13px;
  color: #606266;
  background: #f5f7fa;
  padding: 6px 12px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  font-weight: 500;
  transition: all 0.2s ease;
}

.detail-item:hover {
  background: #e4e7ed;
  border-color: #c0c4cc;
}

.tab-content {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
}

.member-detail-tabs {
  width: 100%;
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-tabs__nav-wrap) {
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-tabs__item) {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  transition: all 0.2s ease;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background: #409eff;
  height: 2px;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}

/* 次级tab样式 */
.points-sub-tabs {
  margin-top: 16px;
}

.points-sub-tabs :deep(.el-tabs__header) {
  margin-bottom: 16px;
}

.points-sub-tabs :deep(.el-tabs__nav-wrap) {
  border-bottom: 1px solid #e4e7ed;
}

.points-sub-tabs :deep(.el-tabs__item) {
  font-size: 13px;
  font-weight: 500;
  color: #606266;
  transition: all 0.2s ease;
}

.points-sub-tabs :deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}



.points-sub-tabs :deep(.el-tabs__active-bar) {
  background: #409eff;
  height: 2px;
}

.points-sub-tabs :deep(.el-tabs__content) {
  padding: 16px 0;
}

/* 费率设置对话框样式 */
.rate-settings-container {
  padding: 20px;
}

.member-info-section {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.info-item span {
  color: #303133;
  font-weight: 500;
}

.settings-selection {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.settings-selection h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.rate-section {
  margin-bottom: 24px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

.rate-section h4 {
  margin: 0;
  padding: 16px;
  background: #f8f9fa;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
}

.rate-content {
  padding: 16px;
}

.base-info {
  margin-bottom: 16px;
  padding: 8px 12px;
  background: #f0f9ff;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.base-info span {
  color: #606266;
  font-size: 14px;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.input-group label {
  font-weight: 500;
  color: #606266;
  min-width: 100px;
}

.table-container {
  margin-top: 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.table-header span {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

/* 表格样式优化 */
.rate-settings-container .el-table {
  border-radius: 4px;
  overflow: hidden;
}

.rate-settings-container .el-table th {
  background: #fafafa;
  color: #606266;
  font-weight: 500;
}

.rate-settings-container .el-table td {
  padding: 8px 0;
}

/* 输入框样式优化 */
.rate-settings-container .el-input-number {
  width: 100%;
}

.rate-settings-container .el-select {
  width: 100%;
}

/* 按钮样式优化 */
.rate-settings-container .el-button--small {
  padding: 6px 12px;
  font-size: 12px;
}

/* 单选按钮组样式 */
.rate-settings-container .el-radio-group {
  display: flex;
  gap: 16px;
}

.rate-settings-container .el-radio {
  margin-right: 0;
}

/* 权限设置样式 */
.member-permissions {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.permission-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 12px;
}

.permission-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
  min-width: 120px;
}

.permission-label .el-icon {
  color: #409eff;
  font-size: 16px;
}

.permission-control {
  flex: 1;
}

.permission-desc {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

/* 开关样式优化 */
.member-permissions .el-switch {
  margin-bottom: 8px;
}

.member-permissions .el-switch__label {
  font-size: 12px;
  color: #606266;
}

/* 汇率设置样式 */
.exchange-rate-settings {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.rate-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.rate-row:last-child {
  margin-bottom: 0;
}

.rate-row label {
  width: 120px;
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.rate-input-group {
  display: flex;
  align-items: center;
  flex: 1;
}

.rate-difference-group {
  display: flex;
  align-items: center;
  flex: 1;
  justify-content: flex-start;
}

.actual-rate-display {
  display: flex;
  align-items: center;
  flex: 1;
}

.rate-note {
  margin-left: 12px;
  font-size: 12px;
  color: #909399;
  font-style: italic;
}

/* 自定义手续费设置样式 */
.custom-fee-settings {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 0;
  border-bottom: 1px solid #e4e7ed;
}

.site-fee-blocks {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 16px;
}

.site-fee-block {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.block-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.site-icon {
  color: #67c23a;
  font-size: 16px;
}

.site-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.add-btn {
  margin-left: auto;
}

.fee-table {
  background: #f8f9fa;
  border-radius: 6px;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 120px;
  background: #f5f7fa;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header-cell {
  font-size: 13px;
  font-weight: 600;
  color: #606266;
}

.table-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 120px;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
  background: white;
}

.table-row:last-child {
  border-bottom: none;
}

.table-cell {
  font-size: 14px;
  color: #303133;
}

.fee-amount {
  color: #409EFF;
  font-weight: 500;
}

.actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}
</style> 